package db

import (
	"context"
	"encoding/json"
	"fmt"
	"github.com/influxdata/influxdb-client-go/v2"
	"github.com/influxdata/influxdb-client-go/v2/api"
	"log"
	"time"
)

type InfluxdDb struct {
	db       *influxdb2.Client
	blocking *api.WriteAPIBlocking
}

var InDb InfluxdDb

func (db *InfluxdDb) DbClose() {
	(*db.db).Close()
}
func (db *InfluxdDb) InitDbPg() {
	client := influxdb2.NewClient(INFLUXDB_HOST+":"+INFLUXDB_PORT, INFLUXDB_TOCKEN)
	blocking := client.WriteAPIBlocking(INFLUXDB_ORG, INFLUXDB_DATABASE)
	db.db = &client
	db.blocking = &blocking
}

func (db *InfluxdDb) InsertPg(data interface{}) {
	switch data.(type) {
	case *DeviceBasics:
		basics := data.(*DeviceBasics)
		info := DataInfo{}
		json.Unmarshal([]byte(basics.Data), &info.DataList)
		m := make(map[string]interface{})
		for _, val := range info.DataList {
			m[val.Key] = val.Val
		}
		point := influxdb2.NewPoint(basics.Name, map[string]string{"type": basics.ParaType}, m, time.Now())
		if len(point.FieldList()) != 0 {
			(*db.blocking).WritePoint(context.Background(), point)
		}
	}

}

func (db *InfluxdDb) WhereFind(sql string, data interface{}) (error, int) {
	queryAPI := (*db.db).QueryAPI(INFLUXDB_ORG)
	query, err := queryAPI.Query(context.Background(), sql)
	if err != nil {
		log.Fatal(err)
		return err, 0
	}
	find := 0
	for query.Next() {
		if find == 0 {
			find = 1
		}

		if query.TableChanged() {
			fmt.Printf("table: %s\n", query.TableMetadata().String())
		}
		value := query.Record().Value()
		switch value.(type) {
		case float64:
			*(data.(*float64)) = value.(float64)
		}
		fmt.Printf("value: %v\n", value)
	}
	if query.Err() != nil {
		fmt.Printf("query parsing error: %s\n", query.Err().Error())
		return query.Err(), 0
	} else {
		if find == 0 {
			return nil, find
		} else {
			return nil, find
		}
	}
}
